jQuery.noConflict();

(function($, PLUGIN_ID) {

    "use strict";

    var config = kintone.plugin.app.getConfig(PLUGIN_ID);
    var rowCount = Number(config["rowCount"]); 

    $(document).ready(function() {
        var terms = {
            'ja': {
                'cf_text_title': '年数自動計算',
                'cf_text_column1': '開始日期のフィールド名称',
                'cf_text_column2': '自動計算年のフィールド名称',
                'cf_text_column3': '次回期限になるカラムの名称',
                'cf_text_column4': '年度の基数',
                'cf_plugin_submit': '保存',
                'cf_plugin_cancel': 'キャンセル',
                'cf_error_message1': 'オプションフィールドの名称を頼みます。',
                'cf_error_message2': '同じカラムの名称を選ぶことができないでください。'
            },
            'en': {
                'cf_text_title': 'Automatic Date Calculator',
                'cf_text_column1': 'Start Date',
                'cf_text_column2': 'Elapsed Years',
                'cf_text_column3': 'Next Due Date',
                'cf_text_column4': 'Offset Year Base',
                'cf_plugin_submit': 'Save',
                'cf_plugin_cancel': 'Cancel',
                'cf_error_message1': 'Please select a field name.',
                'cf_error_message2': 'Please do not select the same field name.'
            },
            'zh': {
                'cf_text_title': '年份自动计算',
                'cf_text_column1': '初始日期字段名称',
                'cf_text_column2': '需要自动计算年份字段名称',
                'cf_text_column3': '下次到期字段名称',
                'cf_text_column4': '年份基数',
                'cf_plugin_submit': '保存',
                'cf_plugin_cancel': '取消',
                'cf_error_message1': '请选择字段名称。',
                'cf_error_message2': '请不要选择相同的字段名称。'
            }
        };

        // To switch the display by the login user's language (English display in the case of Chinese)
        var lang = kintone.getLoginUser().language;
        var i18n = (lang in terms) ? terms[lang] : terms['en'];
        var configHtml = $('#cf-plugin').html();
        var tmpl = $.templates(configHtml);
        $('div#cf-plugin').html(tmpl.render({'terms': i18n}));

        // escape fields vale
        function escapeHtml(htmlstr) {
            return htmlstr.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;").replace(/'/g, "&#39;");
        }

        // set default
        function setDefault(){
            // Has been set up
            for (var i = 0; i < rowCount; i++) {
                var year = config["year" + i];
                var age = config["age" + i];
                var pluginDate = config["pluginDate" + i];
                var yearBase = config["yearBase" + i];
                $('#year-' + i).find("option[value=" + year + "]").prop("selected",true);
                $('#age-' + i).find("option[value=" + age + "]").prop("selected",true);
                $('#pluginDate-' + i).find("option[value=" + pluginDate + "]").prop("selected",true);
                $('#yearBase-' + i).find("option[value=" + yearBase + "]").prop("selected",true);
                // If only one line, hide the delete button
                if (rowCount > i + 1) {
                    var newTrNum = i + 1;
                    // Copy a line
                    $("#trId-0").clone(true).insertAfter($("tbody > tr").eq(newTrNum));
                    // Add ID to new line
                    $("tbody > tr").eq(newTrNum + 1).attr('id','trId-' + newTrNum);
                    var newRow = $('#trId-' + newTrNum);
                    // Add ID to each selection box
                    newRow.find("select:eq(0)").attr('id','year-' + newTrNum);
                    newRow.find("select:eq(1)").attr('id','age-' + newTrNum);
                    newRow.find("select:eq(2)").attr('id','pluginDate-' + newTrNum);
                    newRow.find("select:eq(3)").attr('id','yearBase-' + newTrNum);
                    // Empty the new line
                    newRow.find('select').val('0');
                    newRow.find("span").css('display','none');
                }
            }

            if (rowCount > 1){
                $(".kintoneplugin-button-remove-row-image").show();
            }
            else
            {
                $(".kintoneplugin-button-remove-row-image").hide();
            }
        }

        //set fields to selects
        function setThisfields(resp) {
            //console.log(resp.properties);
            for (var key in resp.properties) {
                if (!resp.properties.hasOwnProperty(key)) continue;
                var prop = resp.properties[key];
                var $option = $("<option>");
                $option.attr("value", escapeHtml(prop.code));
                $option.attr("name", escapeHtml(prop.type));
                if (prop.label) {
                    $option.text(escapeHtml(prop.label));
                }
                
                switch (prop.type) {
                    case "NUMBER":
                        $('select:eq(1)').append($option.clone());
                        break;
                    case "DATE":
                        $('select:eq(0)').append($option.clone());
                        $('select:eq(2)').append($option.clone());
                        break;
                    default:
                        break;
                }
            }
            setDefault();
        }

        //GET fields From this APP
        var url = kintone.api.url('/k/v1/preview/app/form/fields', true);
        var body = {
            app: kintone.app.getId()
        };
        kintone.api(url, 'GET', body, function(resp) {
            // success:
            setThisfields(resp);
        });

        // Add a line
        $("#tableId").on("click", ".kintoneplugin-button-add-row-image", function(){
            rowCount = $("#tableId").find("tr").length-1;
            var maxTrNum = 0;
            $('tr[id^="trId-"]').each(function() {
                var trId = $(this).attr('id');
                var trNum = parseInt(trId.replace(/[^0-9]/ig,""));
                maxTrNum = trNum > maxTrNum ? trNum : maxTrNum; 
            });
            var newTrNum = maxTrNum + 1;
            var thisTrId = $(this).parents("tr").attr("id");
            var newRow = $('#' + thisTrId).clone();
            newRow.attr('id','trId-' + newTrNum);
            newRow.find("select:eq(0)").attr('id','year-' + newTrNum);
            newRow.find("select:eq(1)").attr('id','age-' + newTrNum);
            newRow.find("select:eq(2)").attr('id','pluginDate-' + newTrNum);
            newRow.find("select:eq(3)").attr('id','yearBase-' + newTrNum);
            newRow.find("select").val('0');
            newRow.find("span").css('display','none');
            $("#" + thisTrId).after(newRow);
            rowCount ++;
            // More than 1 rows, display delete button
            if(rowCount >1) {
                $(".kintoneplugin-button-remove-row-image").show();
            }
        });

        // Delete a line
        $("#tableId").on("click", ".kintoneplugin-button-remove-row-image", function(){
            var thisTrId = $(this).parents("tr").attr("id");
            $("#"+thisTrId).remove();
            rowCount = $("#tableId").find("tr").length-1;
            //only one line,hide delete button 
            if(rowCount <= 1) {
                $(".kintoneplugin-button-remove-row-image").hide();
            }
        });

        // Click "Save" to enter the settings
        $('#setting_submit').click(function() {
            $('.cf-plugin-errormessage1, .cf-plugin-errormessage2').css('display','none');
            var config = {};
            rowCount = $("#tableId").find("tr").length-1;
            config['rowCount'] = String(rowCount);
            var maxTrNum = 0;
            $('tr[id^="trId-"]').each(function() {
                var trId = $(this).attr('id');
                var trNum = parseInt(trId.replace(/[^0-9]/ig,""));
                maxTrNum = trNum > maxTrNum ? trNum : maxTrNum; 
            });
            // Find the contents of the settings
            var i = 0;
            for(var j = 0; j <= maxTrNum; j++) {
                if ($('#trId-' + j).length == 0) { continue; }
                else {
                    config['year' + i] = $('#year-' + j).find('option:selected').val();
                    config['age' + i] = $('#age-' + j).find('option:selected').val();
                    config['pluginDate' + i] = $('#pluginDate-' + j).find('option:selected').val();
                    config['yearBase' + i] = $('#yearBase-' + j).find('option:selected').val();
                    i++;
                }
            }
            var emptyError = 0;
            var repeatError = 0;
            $(".kintoneplugin-table-td-control").each(function() {
                var thisTd = $(this);
                var thisSelected = thisTd.find('select option:selected').text();

                $(".kintoneplugin-table-td-control").each(function() {
                    var repeatSelected = $(this).find('select option:selected').text();
                    var yearBaseSelected = $(this).find('select[id^="yearBase-"] option:selected').text();

                    // Check 1:1 to 3 columns must be selected.
                    if (thisSelected == '-----') {
                        thisTd.find('.cf-plugin-errormessage1').css('display','inline-block');
                        emptyError++;
                    }
                    //Check 2/3:Each value is unique except for the fourth column.
                    else if ( thisSelected == repeatSelected && thisSelected !=yearBaseSelected ) {
                        if ($(this).find("select").eq(0).attr("id") != thisTd.find("select").eq(0).attr("id")) {
                            thisTd.find('.cf-plugin-errormessage2').css('display','inline-block');
                            repeatError++;
                        }
                    }
                });
            });
            if (emptyError > 0 || repeatError > 1){
                return;
            }

            // Passing the settings to the application
            kintone.plugin.app.setConfig(config);
        });

        // Click "Cancel" to return to the previous page
        $('#setting_cancel').click(function() {
            if(window.confirm('Are you sure to cancel this setting?')){
                history.back();
              }else{
                return;
             }
        });
    });

})(jQuery, kintone.$PLUGIN_ID);